package com.fjrz.bbxwj.main.mine

import android.Manifest
import android.app.Activity
import android.content.Intent
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ActivityUtils
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.mode.vm.UserViewModel
import com.fjrz.bbxwj.popup.ProgressPopup
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.view.LoadingDialog
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.code
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.view.DialogHintPopup
import com.tbruyelle.rxpermissions3.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import kotlinx.android.synthetic.main.activity_access_2.*
import kotlinx.android.synthetic.main.activity_info_auth.*

class UserAuthActivity : ViewModeActivity<UserViewModel>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, UserAuthActivity::class.java)
            activity.startActivity(intent)
        }
    }

    private val mProgressPopup: ProgressPopup by lazy {
        ProgressPopup(context = this, onConfirm = {

        }, onCancel = {
            mProgressPopup.dismiss()
            viewModel.dispose.clear()
        })
    }


    private val hintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = this,
            onConfirm = {
                hintPopup.dismiss()
                finish()
            },
            onCancel = {
            })
    }

    private var idCardFrontImage: String? = null
    private var idCardBackImage: String? = null

    override val layoutResId: Int
        get() = R.layout.activity_info_auth

    override fun viewModel(): UserViewModel {
        return createViewModel()
    }

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, view = flAuthBar)
    }

    override fun initView() {

        ivAuthBack.setOnClickListener { this.finish() }

        ivAuthIdentity1.setOnClickListener {
            val rxPermissions = RxPermissions(this)
            rxPermissions.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ).subscribe {
                if (!it) {
                    toast(message = "请到设置中开启相关权限")
                } else {
                    Matisse.from((this))
                        .choose(MimeType.ofImage())
                        .countable((true))
                        .maxSelectable(1)
                        .imageEngine(GlideEngine())
                        .theme(R.style.Matisse_Zhihu1)
                        .forResult((100))
                }
            }
        }

        ivAuthIdentity2.setOnClickListener {
            val rxPermissions = RxPermissions(this)
            rxPermissions.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ).subscribe {
                if (!it) {
                    toast(message = "请到设置中开启相关权限")
                } else {
                    Matisse.from((this))
                        .choose(MimeType.ofImage())
                        .countable((true))
                        .maxSelectable(1)
                        .imageEngine(GlideEngine())
                        .theme(R.style.Matisse_Zhihu1)
                        .forResult((101))
                }
            }
        }

        tvAuthName.addTextChangedListener {
            tvAuthSubmit.isEnabled =
                !it.isNullOrEmpty() && !tvAuthIdCode.text.isNullOrEmpty() && !idCardFrontImage.isNullOrEmpty() && !idCardBackImage.isNullOrEmpty()
        }
        tvAuthIdCode.addTextChangedListener {
            tvAuthSubmit.isEnabled =
                !it.isNullOrEmpty() && !tvAuthName.text.isNullOrEmpty() && !idCardFrontImage.isNullOrEmpty() && !idCardBackImage.isNullOrEmpty()
        }

        tvAuthSubmit.setOnClickListener {
            viewModel.userCertificate(
                tvAuthName.text.toString(),
                tvAuthIdCode.text.toString(),
                idCardFrontImage ?: return@setOnClickListener,
                idCardBackImage ?: return@setOnClickListener
            )
        }
    }

    override fun initViewMode() {

        viewModel.userCertificateLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (responseStatus2LiveData(response.status, response.throwable) != Status.SUCCESS)
                return@Observer
            hintPopup.setTextTitle("提示")
                .setTextMessage(response.httpData?.msg ?: "上传成功，请等待平台审核")
                .setTextConfirm("好的")
                .isTextCancelGone(true)
                .setBackPressEnable(false)
                .setOutSideDismiss(false)
                .showPopupWindow()
        })

        viewModel.uploadLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.START) {
                if (!mProgressPopup.isShowing)
                    mProgressPopup.showPopupWindow()
                mProgressPopup.resetProgress()
            } else if (response.status == Status.FAILURE) {
                mProgressPopup.dismiss()
                toast(response.throwable?.code, response.throwable?.msg)

                if (mImageAction == 100) {
                    ivAuthIdentity1.setImageResource(R.mipmap.ic_18011)
                } else if (mImageAction == 101) {
                    ivAuthIdentity1.setImageResource(R.mipmap.ic_18012)
                }
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            mProgressPopup.dismiss()
            response.httpData?.data?.let {
                if (mImageAction == 100) {
                    idCardFrontImage = it.url
                } else if (mImageAction == 101) {
                    idCardBackImage = it.url
                }
                tvAuthSubmit.isEnabled =
                    !tvAuthIdCode.text.isNullOrEmpty() && !tvAuthName.text.isNullOrEmpty() && !idCardFrontImage.isNullOrEmpty() && !idCardBackImage.isNullOrEmpty()
            }
        })

        viewModel.progressLiveData.observe(this as LifecycleOwner, Observer { progress ->
            mProgressPopup.setProgress(progress)
        })
    }

    private var mImageAction: Int = 100

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            val pathList: MutableList<String> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            ivAuthIdentity1.loadRoundImage(pathList[0], radius = 30)
            mImageAction = 100
            viewModel.commonUpload(pathList[0])
        } else if (requestCode == 101 && resultCode == RESULT_OK) {
            val pathList: MutableList<String> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            ivAuthIdentity2.loadRoundImage(pathList[0], radius = 30)
            mImageAction = 101
            viewModel.commonUpload(pathList[0])
        }
    }

    private fun responseStatus2LiveData(status: Status, throwable: Throwable?): Status {
        if (status == Status.START) LoadingDialog.show(
            context = this, resId = R.layout.dialog_load_style_1
        ) else if (status == Status.FAILURE) {
            LoadingDialog.dismiss()
            toast(throwable?.code, throwable?.msg)
        } else {
            LoadingDialog.dismiss()
        }
        return status
    }
}